package com.shijie.component;

import java.util.Set;
import java.util.UUID;

import com.shijie.component.redis.RedisClient;
import com.shijie.component.redis.RedisKey;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.shijie.core.constants.PnConstant;
import com.shijie.domain.entity.Admins;
import com.shijie.service.RolesService;
import com.shijie.utils.CommonUtil;

/**
 * Created with Yang Huan
 * Date: 2017/3/2
 * Time: 11:34
 */
@Component
public class ErpUserService {

    @Autowired
    private RolesService rolesService;
    @Autowired
    private RedisClient redisClient;


    public void createToken(Admins admin) {
        String token = String.format(PnConstant.CACHE_TOKEN_KEY, "erp", UUID.randomUUID().toString());
        
        //查询用户权限并插入到cache 方便后面权限校验
        Set<String> set = rolesService.selectPermsByUserId(admin.getId());
        redisClient.put(String.format(RedisKey.ERP_PERMISSION_CACHE, admin.getId()), set, 3600l);
        redisClient.put(String.format(RedisKey.ERP_LOGIN_CACHE, token), admin, 3600l);

        CommonUtil.getResponse().setHeader(String.format(PnConstant.HEADER_TOKEN_KEY, "erp"), token);
    }

    public Boolean isLogin() {
        return null != getUserId();
    }

    public String getUserName() {
    	Admins user = this.getAdmin();
        if (user == null) return null;
        return user.getUserName() == null ? user.getLoginName() : user.getUserName();
    }
    
    public Integer getUserId() {
    	Admins admin = this.getAdmin();
    	if(admin != null){
    		return admin.getId();
    	}
    	return null;
    }

    public Admins getAdmin() {
        String token = CommonUtil.getRequest().getHeader(String.format(PnConstant.HEADER_TOKEN_KEY, "erp"));
        if (!StringUtils.isEmpty(token)) {
            if (redisClient.hasKey(String.format(RedisKey.ERP_LOGIN_CACHE, token))) {
                Admins admin = redisClient.get(String.format(RedisKey.ERP_LOGIN_CACHE, token));
                if (admin != null) {
                    // 刷新30分钟的缓存信息
                    Set<String> permissions = redisClient.get(String.format(RedisKey.ERP_PERMISSION_CACHE, admin.getId()));
                    redisClient.put(String.format(RedisKey.ERP_PERMISSION_CACHE, admin.getId()), permissions, 3600l);
                    redisClient.put(String.format(RedisKey.ERP_LOGIN_CACHE, token), admin, 3600l);
                    return admin;
                }
            }
        }
        return null;
    }

}
